Skip to content

fix: refresh auth context for stateful HTTP requests#2221

Closed
lavish0000 wants to merge 5 commits intomodelcontextprotocol:mainfrom
lavish0000:fix/stateful-auth-context-2208
Closed

fix: refresh auth context for stateful HTTP requests#2221
lavish0000 wants to merge 5 commits intomodelcontextprotocol:mainfrom
lavish0000:fix/stateful-auth-context-2208

Conversation

@lavish0000
Copy link
Copy Markdown

Summary

  • bind auth_context_var from the current request metadata at low-level request dispatch time
  • clear the auth context for requests that do not carry an authenticated user
  • add an integration regression test that changes bearer tokens mid-session in stateful streamable HTTP

Problem

In stateful streamable HTTP mode, request handlers can run inside task-group tasks whose context was copied from the session-creating request. That means get_access_token() keeps returning the bearer token from the first request in the session, even after later requests send a different Authorization header.

Fix

Each handled request already carries its Starlette request object in ServerMessageMetadata.request_context. At dispatch time, the low-level server now reads the authenticated user from that request scope and binds auth_context_var for the duration of the handler call. This refreshes get_access_token() on every request while preserving the existing behavior for unauthenticated apps.

Validation

  • reproduced the bug locally on current main with an in-process ASGI app and a mutable bearer auth client (token-A stayed visible after switching to token-B)
  • uv run pytest tests/issues/test_2208_stateful_auth_context.py tests/server/auth/middleware/test_auth_context.py tests/shared/test_streamable_http.py -k "2208 or auth_context or request_context_propagation or request_context_isolation"
  • uv run ruff check src/mcp/server/lowlevel/server.py tests/issues/test_2208_stateful_auth_context.py
  • uv run ruff format --check src/mcp/server/lowlevel/server.py tests/issues/test_2208_stateful_auth_context.py
  • uv run pyright src/mcp/server/lowlevel/server.py tests/issues/test_2208_stateful_auth_context.py

@maxisbey
Copy link
Copy Markdown
Contributor

Thanks for the PR! Per our CONTRIBUTING.md, PRs require a corresponding issue with the ready for work label so we can agree on scope before reviewing code. Closing for now — please open an issue first and re-submit once it's triaged.

AI Disclaimer

@maxisbey maxisbey closed this Mar 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants